const CACHE_NAME = 'news-app-cache-v1';
const urlsToCache = [
    '/index.html',
    '/main.js',
    '/demo.json'
];

// 注册阶段
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => {
                return cache.addAll(urlsToCache);
            })
    );
});

// 激活阶段
self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames.map((cacheName) => {
                    if (cacheName !== CACHE_NAME) {
                        return caches.delete(cacheName);
                    }
                })
            );
        })
    );
});

// 拦截请求
self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request)
            .then(cachedResponse => {
                // 如果缓存中存在请求的响应，则直接返回缓存的响应
                if (cachedResponse) {
                    console.log('缓存数据', event.request.url);
                    return cachedResponse;
                }

                // 如果缓存中不存在请求的响应，则继续向网络发出请求
                return fetch(event.request)
                    .then(networkResponse => {
                        // 将从网络获取到的响应添加到缓存中
                        return caches.open('dynamic-cache')
                            .then(cache => {
                                cache.put(event.request, networkResponse.clone());
                                return networkResponse;
                            });
                    })
                    .catch(error => {
                        console.error('Fetch 失败', error);
                        // 如果网络请求失败，可以返回一个自定义的响应
                        return new Response('Network request failed!', {
                            status: 500,
                            statusText: '网络请求失败'
                        });
                    });
            })
    );
});